<?php

namespace console\controllers;

use Yii;
use yii\db\Exception;
use yii\helpers\ArrayHelper;
use common\models\book\Holiday;

/**
 * 计划任务-节假日更新
 *
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class HolidayController extends \yii\console\Controller {

    public function getHoliday($page = 1, $size = 20) {
        if (!$page) {
            $page = 1;
        }
        if (!$size) {
            $size = 20;
        }
        /* @var $curl \common\components\http\Curl */
        $curl = Yii::$app->curl;
        $curl->setGetParams([
            'year' => date('Y'),
            'order_by' => 1,
            'cn' => 1,
            'page' => $page,
            'size' => $size,
        ]);
        return $curl->get('https://api.apihubs.cn/holiday/get', false);
    }

    /**
     * @return mixed
     */
    public function actionIndex() {
        $data = $this->getHoliday();
        $total = ArrayHelper::getValue($data, 'data.total');
        $size = 20;
        $pagesize = ceil($total / $size);

        $map = [
            'holiday' => [
                'name' => 'holiday_cn',
                'format' => function($data) {
                    return str_replace('非节假日', '', $data);
                },
            ],
            'holiday_or' => [
                'name' => 'holiday_or_cn',
                'format' => function($data) {
                    return str_replace('非节假日', '', $data);
                },
            ],
            'overtime' => [
                'name' => 'holiday_overtime',
                'format' => function($data) {
                    return $data > 10 ? 1 : 0;
                },
            ],
            'lunar_year' => 'lunar_year',
            'lunar_date' => 'lunar_date_cn',
            //
            'workday' => [
                'name' => 'workday',
                'format' => function($data) {
                    return abs($data - 2);
                },
            ],
            'legal' => [
                'name' => 'holiday_legal',
                'format' => function($data) {
                    return abs($data - 2);
                },
            ],
            'recess' => [
                'name' => 'holiday_recess',
                'format' => function($data) {
                    return abs($data - 2);
                },
            ],
            'today' => [
                'name' => 'holiday_today',
                'format' => function($data) {
                    return abs($data - 2);
                },
            ],
        ];
        for ($page = 1; $page <= $pagesize; $page++) {
            $data = $this->getHoliday($page, $size);
            $holidays = ArrayHelper::getValue($data, 'data.list', []);
            if (empty($holidays)) {
                continue;
            }
            //执行任务
            $transaction = Yii::$app->db->beginTransaction();
            try {
                foreach ($holidays as $holiday) {
                    $date = strtotime(ArrayHelper::getValue($holiday, 'date'));
                    $model = Holiday::findOrNew([
                        'date' => date('Y-m-d', $date)
                    ]);
                    foreach ($map as $attribute => $item) {
                        if (is_array($item)) {
                            $value = ArrayHelper::getValue($holiday, $item['name']);
                            $model->$attribute = call_user_func($item['format'], $value);
                        } else {
                            $model->$attribute = ArrayHelper::getValue($holiday, $item);
                        }
                    }
                    if ($model->holiday == $model->holiday_or && !$model->today) {
                        $model->holiday_or = null;
                    }
                    if ($model->workday) {
                        $model->status = 10;
                    }
                    if (!$model->save()) {
                        throw new Exception($model->getErrorMsg());
                    }
                }
                $transaction->commit();
            } catch (Exception $e) {
                // 记录回滚（事务回滚）
                $transaction->rollBack();
                static::taskLog([
                    'message' => '计划任务状态更新失败',
                    'error' => $e->getMessage(),
                ]);
            }
        }
        return true;
    }

    /**
     * 自动执行任务
     * @param mixed $message
     * @param CronTask $model
     * @return mixed
     */
    protected static function taskLog($message) {
        Yii::error([
            'RUNTIME' => date('Y-m-d H:i:s'),
            'MESSAGE' => $message,
        ], 'cron');
    }

}
